package com.instalinks.android.lib;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.Context;

public class NotificationQueue {

	private String mFileName = "";
	private int mQueueSize = 10;
	protected final Context mContext;

	private ArrayList<String> mQueue;
	
	public NotificationQueue(Context context, String queueName, int queueSize) {

		this.mContext = context;
		this.mFileName = queueName;
		this.mQueueSize = queueSize;

		try {
			readQueue();
		} catch (Exception e) {
			mQueue = new ArrayList<String>();
		}
	}

	protected Context getContext() {
		return this.mContext;
	}

	public void repopulate(){
		try {
			readQueue();
		} catch (Exception e) {
			mQueue = new ArrayList<String>();
		}
	}
	
	
	public boolean isExists() {
		try {
			readQueue();
			return true;
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		} catch (ClassNotFoundException cnf) {
			return true;
		}
	}

	public String getValue(int index) {
		if (index<0 || index>=mQueue.size())
			return "";
		else
			return mQueue.get(index);
	}
	
	public void push(String value) throws FileNotFoundException, IOException{
		if(mQueue.size() == mQueueSize){
			mQueue.remove(0);
		}
		DateFormat dateFormat = new SimpleDateFormat("MM/dd HH:mm:ss");
		Date date = new Date();

		mQueue.add(dateFormat.format(date) + "; " + value);
		
		this.saveQueue();
	}

	public int getSize(){
		return mQueue.size();
	}
	public void clearQueue() throws FileNotFoundException, IOException {
		synchronized (this) {
			mQueue.clear();
			saveQueue();
		}
	}

	public boolean deleteQueue() {
		synchronized (this) {
			return mContext.deleteFile(mFileName);
		}
	}
	
	@SuppressWarnings("unchecked")
	private void readQueue() throws FileNotFoundException, IOException,
			ClassNotFoundException {
		synchronized (this) {
			FileInputStream fis = mContext.openFileInput(mFileName);
			ObjectInputStream ois = new ObjectInputStream(fis);
			mQueue = (ArrayList<String>) ois.readObject();

			ois.close();
			fis.close();
		}
	}

	private void saveQueue() throws FileNotFoundException, IOException {
		synchronized (this) {
			FileOutputStream fos = mContext.openFileOutput(mFileName,
					Context.MODE_PRIVATE);
			ObjectOutputStream oos = new ObjectOutputStream(fos);

			oos.writeObject(mQueue);

			oos.close();
			fos.close();
		}
	}
}
